package util

import (
	"bytes"
	"fmt"
	"net"
)

func Quary(dial net.Conn, key []byte) ([]byte, error) {
	buffer := bytes.NewBuffer(nil)
	_, err := dial.Write([]byte(fmt.Sprintf("get %s;", key)))
	if err != nil {
		return nil, err
	}

	for {
		chunk := make([]byte, 4096)
		n, err := dial.Read(chunk)
		if err != nil {
			return nil, err
		}

		buffer.Write(chunk[:n])
		if string(chunk[n-1]) == ";" {
			break
		}
	}
	val := buffer.String()
	val = val[:len(val)-1]
	return []byte(val), nil
}

func Set(dial net.Conn, key []byte, val []byte) ([]byte, error) {
	buffer := bytes.NewBuffer(nil)
	_, err := dial.Write([]byte(fmt.Sprintf("set %s %s;", key, val)))
	if err != nil {
		return nil, err
	}

	for {
		chunk := make([]byte, 4096)
		n, err := dial.Read(chunk)
		if err != nil {
			return nil, err
		}

		buffer.Write(chunk[:n])
		if string(chunk[n-1]) == ";" {
			break
		}
	}
	msg := buffer.String()
	msg = msg[:len(msg)-1]
	return []byte(msg), nil
}
